/*
 * Copyright (c) 2012 Robert Burrell Donkin robertburrelldonkin.name
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
 * and associated documentation files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, publish, distribute, 
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 
 * is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or 
 * substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING 
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 * 
 */
package sekhmet.audio.sink;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.BlockingQueue;

import sekhmet.audio.data.SignalData;

public class InputStreamSink extends InputStream {
	
	private static final int END_OF_STREAM = -1;

	private final BlockingQueue<SignalData> queue;

	private InputStream delegate;
	private boolean endOfStream = false;
	
	public InputStreamSink(BlockingQueue<SignalData> queue) {
		super();
		this.queue = queue;
	}

	@Override
	public int read() throws IOException {
		if (endOfStream) return END_OF_STREAM;
		if (delegate == null) {
			next();
		}
		
		if (endOfStream) return END_OF_STREAM;
		final int result = delegate.read();
		if (result == END_OF_STREAM) {
			return read();
		}
		return result;
	}

	private void next() {
		try {
			SignalData data = queue.take();
			switch (data.getType()) {
				case END:
					endOfStream = true;
					break;
				case DATA:
					delegate = data.getBuffer().inputStream();
					break;
			    default:
			    	next();
			    	break;
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
			next();
		}
	}

	@Override
	public int read(byte[] b, int off, int len) throws IOException {
		if (endOfStream) return END_OF_STREAM;
		if (delegate == null) {
			next();
		}
		
		if (endOfStream) return END_OF_STREAM;
		final int result = delegate.read();
		if (result == END_OF_STREAM) {
			return read(b, off, len);
		}
		return result;
	}

	@Override
	public int read(byte[] b) throws IOException {
		if (endOfStream) return END_OF_STREAM;
		if (delegate == null) {
			next();
		}
		
		if (endOfStream) return END_OF_STREAM;
		final int result = delegate.read();
		if (result == END_OF_STREAM) {
			return read(b);
		}
		return result;
	}
}
